package com.delayqueue.common.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.List;

public class ByteToStringDecoder extends ByteToMessageDecoder {
    private Charset charset;

    public ByteToStringDecoder() {
        this.charset = CharsetUtil.UTF_8;
    }

    public ByteToStringDecoder(Charset charset) {
        this.charset = charset;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() >= 4) {
            int len = byteBuf.readInt();
            ByteBuf contentBytes = byteBuf.readBytes(len);
            list.add(contentBytes.toString(charset));
        }
    }
}
